<template>
  <div v-loading="loading">
    <div class="detail_box">

    <!-- 页面的权限 -->
      <div class="group_box" v-if="treeData&&treeData.length!==0">
        <div v-for="(item, indexkey) in treeData" :key="item.id">
          <div class="lab_line">
            <el-checkbox class="check1" style="font-weight: 600; " v-model='menusIds' :label="item.id" @change="handleCheck(1,indexkey,'',$event)">
              {{item.name}}
            </el-checkbox>
          </div>
          <div class="child_box" :class="{'flex_box':!item.childPermissions[0].childPermissions}" v-if="item.childPermissions">
            <div v-for="(list,indexlist) in item.childPermissions" class="line_check" :key="list.id">
              <div class="second_box">
                <el-checkbox class="check2" @change="handleCheck(2,indexkey,indexlist,$event)" v-model="menusIds" :label="list.id">
                  {{list.name}}
                </el-checkbox>
              </div>
              <div class="child_box third_box flex_box" v-if="list.childPermissions">
                <div v-for="(child,indexchild) in list.childPermissions" class="child_check" :key="child.id">
                  <el-checkbox class="check3" @change="handleCheck(3,indexkey,indexlist,$event)" v-model="menusIds" :label="child.id">
                    {{child.name}}
                  </el-checkbox>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="group_box">暂无菜单</div>
    </div>
    <div class="bottom_btn">
      <span class="save_btn" @click="addTree">保存</span>
    </div>
  </div>
</template>

<script>
//获取系统的权限内容
  import {getRolePermission,getTree,assignPermission} from "../../../api/sys/permission";

  export default {
    props:['roleId'],

    data() {
      return {
        treeData: [],
        menusIds: [],
        all:[],
        userInfo:{},
        loading: false,
      }
    },
    mounted() {
      this.getTree();
      this.getRoleTree();
      if (localStorage.getItem('water_user')){
        let info = localStorage.getItem('water_user')
        this.userInfo = info?JSON.parse(info).roleIds:'';
      }
    },
    methods: {
      // 获取树形权限信息
      getTree() {
        let that = this;
        that.loading = true;
        let param = {
          name:'',
          type:''
        }
        getTree(param).then((res)=>{
          that.treeData = res ?res:[];
          that.loading = false;

        }).catch(() => {
          that.loading = false;
        });
      },

      // 回显已勾选数据
      getRoleTree() {
        let that = this;

        //获取当前觉得已经拥有的权限
        getRolePermission(that.roleId).then((res)=>{
          if (res){
            let arr = '['+res+']';
            //转化成为数组
            that.menusIds = JSON.parse(arr);
          }else {
            that.menusIds = []
          }
        }).catch(() => { });
      },

      // 分配权限
      addTree(){
        let that = this;
        let param = {
          roleId:that.roleId,
          rolePermissions:that.selectionChange(that.menusIds)
        }
        that.loading = true;
        assignPermission(param).then(response => {
          that.$message.success({
            message:'操作成功',
            duration:1500
          });
          that.$emit('listenToChild',false);
          if (that.userInfo&&that.userInfo.indexOf(that.roleId)!==-1){
            that.$router.push('/');
            localStorage.clear();
          }
          that.isChange = false
          that.loading = false;
        }).catch((e) => {
          that.loading = false;
        });
      },

      // 多选
      selectionChange(val) {
        let data = '';
        val.forEach((item, i) => {
          data = data + (i > 0 ? ',' : '') + item
        });
        return data
      },

      // 处理选择事件
      handleCheck(type, a, b,val) { // 多选框
        let that = this;
        if (type === 3) { // 二级菜单点击
          let index = 0;
          that.treeData[a].childPermissions[b].childPermissions.map(item => {
            if (that.menusIds.indexOf(item.id) > -1) {// 仅选三级，一、二级不变
              index += 1;
            }
          });
          if (index > 0) {
            // 选了三级，一级同时勾上
            if (that.menusIds.indexOf(that.treeData[a].id) < 0) {
              that.menusIds.push(that.treeData[a].id);
            }
            // 选了三级，二级同时勾上
            if (that.menusIds.indexOf(that.treeData[a].childPermissions[b].id) < 0) {
              that.menusIds.push(that.treeData[a].childPermissions[b].id);
            }
          } else {
            // 取消三级（只有一个二级：一级同时取消）
            if (that.treeData[a].childPermissions.length===1){
              if (that.menusIds.indexOf(that.treeData[a].id) > -1) {
                that.menusIds.splice(that.menusIds.indexOf(that.treeData[a].id), 1);
              }
            }else {
              // 多个二级：判断是否有其他二级被勾选再取消
              let num = 0;
              that.treeData[a].childPermissions.map(item => {
                if (that.menusIds.indexOf(item.id) > -1) {// 仅选三级，一、二级不变
                  num += 1;
                }
              });
              if (num<2){
                that.menusIds.splice(that.menusIds.indexOf(that.treeData[a].id), 1);
              }
            }
            // 取消三级，二级同时取消
            if (that.menusIds.indexOf(that.treeData[a].childPermissions[b].id) > -1) {
              that.menusIds.splice(that.menusIds.indexOf(that.treeData[a].childPermissions[b].id), 1);
            }
          }
        }else if (type === 2) { // 二级菜单点击
          let index = 0;
          that.treeData[a].childPermissions.map(item => {
            if (that.menusIds.indexOf(item.id) > -1) {// 仅选二级，一级不变
              index += 1;
            }
          });
          if (val) {
            // 选了二级，一级同时勾上
            if (that.menusIds.indexOf(that.treeData[a].id) < 0) {
              that.menusIds.push(that.treeData[a].id);
            }
            // 选了二级，三级全部勾上
            if (that.treeData[a].childPermissions[b].childPermissions){
              that.treeData[a].childPermissions[b].childPermissions.map(item => {
                if (that.menusIds.findIndex((n) => n === item.id) < 0) {
                  that.menusIds.push(item.id)
                }
              })
            }
          } else { // 取消二级，一级同时取消
            if (index===0&&that.menusIds.indexOf(that.treeData[a].id) > -1) {
              that.menusIds.splice(that.menusIds.indexOf(that.treeData[a].id), 1);
            }
            // 取消二级，三级全部取消
            if (that.treeData[a].childPermissions[b].childPermissions) {
              that.treeData[a].childPermissions[b].childPermissions.map(item => {
                if (that.menusIds.findIndex((n) => n === item.id) > -1) {
                  that.menusIds.splice(that.menusIds.findIndex((n) => n === item.id), 1);
                }
              })
            }else {
              that.menusIds.splice(that.menusIds.findIndex((n) => n === that.treeData[a].childPermissions[b].id), 1);
            }
          }
        } else { // 一级菜单勾选
          if (that.menusIds.indexOf(that.treeData[a].id) > -1) {
            if (that.treeData[a].childPermissions&&that.treeData[a].childPermissions.length===0) {
              that.menusIds.push(that.treeData[a].id)
            }else {
              // 选了一级，二级全部选上
              if (that.treeData[a].childPermissions){
                that.treeData[a].childPermissions.map(item => {
                  if (that.menusIds.findIndex((n) => n === item.id) < 0) {
                    that.menusIds.push(item.id)
                    // 选了一级，三级全部选上
                    if (item.childPermissions){
                      item.childPermissions.map(child => {
                        if (that.menusIds.findIndex((n) => n === child.id) < 0) {
                          that.menusIds.push(child.id)
                        }
                      })
                    }
                  }
                })
              }
            }
          } else { //一级菜单取消
            if (that.treeData[a].childPermissions) {
              that.treeData[a].childPermissions.map(item => {
                if (that.menusIds.findIndex((n) => n === item.id) > -1) {
                  that.menusIds.splice(that.menusIds.findIndex((n) => n === item.id), 1);
                  if (item.childPermissions){
                    item.childPermissions.map(child => {
                      if (that.menusIds.findIndex((n) => n === child.id)>-1) {
                        that.menusIds.splice(that.menusIds.findIndex((n) => n === child.id), 1);
                      }
                    })
                  }
                }
              })
            }else {
              that.menusIds.splice(that.menusIds.findIndex((n) => n === that.treeData[a].id), 1);
            }
          }
        }
      },
    }
  }
</script>

<style>
  .el-dialog__body {
    padding: 0 20px 10px !important;
  }
</style>
<style scoped>
  .detail_box {
    position: relative;
    width: 100%;
    box-sizing: border-box;
    min-width: 0;
    height: 550px;
    min-height: 550px;
    padding: 0 20px 0 0;
    overflow-y: auto;
  }

  .flex_box {
    display: flex!important;
    flex-wrap: wrap!important;
  }

  .child_box {
    display: block;
    width: 100%;
    margin-bottom: 10px
  }

  .child_box div{
    width: auto;
  }

  .child_box .line_check {
    margin:0 0 15px 20px;
  }

  .child_list {
    display: block;
    width: auto;
  }

  .third_box {
    padding-left: 42px;
  }

  .lab_line {
    line-height: 35px;
    padding-left: 10px;
    margin-bottom: 15px;
    background: #f2f2f2;
  }

  .second_box {
    margin-bottom: 10px;
    padding-left: 15px;
  }

  .bottom_btn {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-top:6px ;
    border-top: 1px solid #f3f3f3;
  }

  .save_btn {
    background: #6687f9;
    color: #fff;
    border-radius: 40px;
    width: 180px;
    line-height: 36px;
    font-size: 14px;
    text-align: center;
    cursor: pointer;
    border: 1px solid #6687f9;
  }

  .save_btn:hover {
    background: #93a8f5;
  }
</style>
